package org.nepu.auth.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaFoxUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.lboot.core.auth.AuthService;
import org.lboot.core.auth.anno.AuthLogin;
import org.lboot.core.domain.ResponseDTO;
import org.lboot.rbac.module.dept.SysDept;
import org.lboot.rbac.module.dept.SysDeptService;
import org.lboot.rbac.module.user.SysUser;
import org.lboot.rbac.module.user.SysUserService;
import org.nepu.auth.params.OAuthParams;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@RestController
@RequestMapping("safe")
@AllArgsConstructor
@Api(tags = "测试接口")
public class NepuAuthController {

    AuthService authService;

    SysUserService userService;

    SysDeptService sysDeptService;

    @SneakyThrows
    @PostMapping(value = "oauth/login")
    @ApiOperation(value = "跳过账号密码登录接口")
    public ResponseDTO<Object> qLogin(@RequestBody OAuthParams params) {
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String url = "https://aqhb.cnooc.com.cn/platformab/api/aqhb-platform/blade-system/user/info";//配置文件中引入的地址
        Map<String, Object> map = new HashMap<>();
        String tokenK = "Basic c2FiZXI6c2FiZXJfc2VjcmV0";
        String Token = params.getToken();
        String tokenV = "";
        //判断是否传入token，如果没有传入token，则从cookie中获取token
        if (Validator.isEmpty(Token)) {
            String s = request.getHeader("Cookie");
            log.info("s:{}",s);
            // 自己生成的TOKEN
            if (s==null){
                String mes = "Token失效";
                return ResponseDTO.wrap(HttpStatus.OK, mes);
            }
            String regex = "saber-access-token=([^;]+)";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(s);
            if (matcher.find()) {
                tokenV = matcher.group(1);
            }else {
                return ResponseDTO.wrap(HttpStatus.UNAUTHORIZED,"Cookie未携带鉴权信息");
            }
        }else {
            log.info("Token:{}",Token);
            tokenV = Token;
        }
        log.info("tokenV:{}",tokenV);
        HttpResponse response = HttpRequest.get(url)
                .header("Authorization", tokenK) // 添加自定义 Authorization 头
                .header("Content-Type", "application/json")       // 设置 Content-Type
                .header("Blade-auth", "bearer "+ tokenV)           // 添加其他自定义头
                .timeout(5000)                                    // 设置超时时间，单位毫秒
                .execute();

        System.out.println("Status Code: " + response.getStatus());
        //判断response.getStatus()是否等于200，如果不等于200，则返回错误信息
        if (response.getStatus() != 200) {
            return ResponseDTO.wrap(HttpStatus.UNAUTHORIZED,"获取用户信息失败");
        }

        System.out.println("Response Body: " + response.body());

        // 将JSON字符串转换为JSONObject
        JSONObject jsonObject = new JSONObject(response.body());

        // 获取"data"对象
        JSONObject dataObject = jsonObject.getJSONObject("data");

        // 获取"account"的值
        String username = dataObject.getStr("account");
        // 获取"id"的值
        String id = dataObject.getStr("id");
        // 获取"nickName"的值
        String nickName = dataObject.getStr("name");

        log.info("username:{}",username);
        StpUtil.login(username);
        Map<String, Object> result = new HashMap<>();
        result.put("id",id);
        result.put("username",username);
        result.put("nickName",nickName);
        result.put("token",StpUtil.getTokenValue());

        return ResponseDTO.succData(result);
    }

}

